<template>
  <div>
    <el-select
      ref="select"
      filterable
      :value="value"
      :filter-method="search"
      clearable
      placeholder="请选择"
      @input="oninput"
      @blur="onblur"
    >
      <el-option
        value=""
        style="height: auto; padding: 0;font-weight:700;"
      >
        <el-tree
          ref="tree"
          node-key="id"
          :data="options"
          :props="defaultProps"
          :filter-node-method="filterNode"
          :expand-on-click-node="false"
          style="width: 100%"
          @node-click="handleNodeClick"
        />
      </el-option>
    </el-select>
  </div>
</template>

<script>
import { getDepartTree } from '@/api/base'
export default {
  name: 'TreeSelect',
  props: {
    value: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      options: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  mounted() {
    this.getTree()
  },
  methods: {
    handleNodeClick(data) {
      this.$emit('input', data.name)
      this.$emit('update:id', data.id)
      this.$refs.select.blur()
    },
    search(val) {
      this.$refs.tree.filter(val)
      this.$emit('input', val)
    },
    filterNode(value, data, node) {
      if (!value) return true
      let parentNode = node.parent
      let labels = [node.label]
      let level = 1
      while (level < node.level) {
        labels = [...labels, parentNode.label]
        parentNode = parentNode.parent
        level++
      }
      return labels.some(label => label.indexOf(value) !== -1)
    },
    async getTree() {
      const res = await getDepartTree()
      this.options = JSON.parse(res)
    },
    oninput() {
      this.$emit('update:id', null)
      this.$emit('input', '')
    },
    onblur() {
      // this.oninput()
      this.$refs.tree.filter()
    }
  }
}
</script>
<style lang="scss" scoped>
  .el-select{
    width: 100%;
  }
</style>
